#import "StringUtil.h"

@implementation CStringUtil

+(int)NSString2Int:(NSString*)aString defaultValue:(int)aDefaultValue
{
	if (aString==nil) {
		return aDefaultValue;
	}
	
	aDefaultValue=[aString intValue];
	return aDefaultValue;
}

//+(unsigned int)NSStringUInt:(NSString*)aString defaultValue:(unsigned int)aDefaultValue
//{
//	if (aString==nil) {
//		return aDefaultValue;
//	}
//	
//	aDefaultValue=[aString intValue];
//	return aDefaultValue;
//}

+(int)GetDecimalLength:(int)aNumber
{
	int length=1;
	
	while (aNumber>=10) 
	{
		int yuShu=aNumber%10;
		aNumber=yuShu;
		
		length++;
	}
	
	return length;
}

+(char*)TransformNSStringToChar:(NSString*)string
{
	char *result;
	int length;
	
	const char *cString=[string UTF8String];
	length=strlen(cString);
	result=(char*)malloc(length+1);
	memcpy(result, cString, length);
	result[length]=0;
	return result;
}

+(NSString*)TransformCharToNSString:(char*)string
{
	NSString *result=[NSString stringWithUTF8String:string];
	return result;
}

+ (NSString*)URLencode:(NSString *)originalString stringEncoding:(NSStringEncoding)stringEncoding {
    //!  @  $  &  (  )  =  +  ~  `  ;  '  :  ,  /  ?
    //%21%40%24%26%28%29%3D%2B%7E%60%3B%27%3A%2C%2F%3F
    NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                            @"@" , @"&" , @"=" , @"+" ,    @"$" , @"," ,
                            @"!", @"'", @"(", @")", @"*", nil];
	
    NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F", @"%3F" , @"%3A" ,
                             @"%40" , @"%26" , @"%3D" , @"%2B" , @"%24" , @"%2C" ,
                             @"%21", @"%27", @"%28", @"%29", @"%2A", nil];
	
    int len = [escapeChars count];
	
    NSMutableString *temp = [[originalString
                              stringByAddingPercentEscapesUsingEncoding:stringEncoding]
                             mutableCopy];
	
    int i;
    for (i = 0; i < len; i++) {
		
        [temp replaceOccurrencesOfString:[escapeChars objectAtIndex:i]
                              withString:[replaceChars objectAtIndex:i]
                                 options:NSLiteralSearch
                                   range:NSMakeRange(0, [temp length])];
    }
	
    NSString *outStr = [NSString stringWithString: temp];
	[temp release];
    return outStr;
}

@end
